<template>
  <el-dialog
    v-model="dialogVisible"
    title="添加员工"
    width="800px"
    :close-on-click-modal="false"
    @close="handleClose"
  >
    <div class="add-employee-container">
      <!-- 用户选择区域 -->
      <div class="user-selection">
        <h4>选择用户</h4>
        <el-form :model="searchForm" label-width="100px">
          <el-form-item label="搜索用户">
            <el-input
              v-model="searchForm.keyword"
              placeholder="输入用户名、姓名或手机号搜索"
              @keyup.enter="handleSearchUser"
            >
              <template #append>
                <el-button @click="handleSearchUser" :loading="userLoading">搜索</el-button>
              </template>
            </el-input>
          </el-form-item>
        </el-form>

        <!-- 用户列表 -->
        <el-table
          :data="userList"
          v-loading="userLoading"
          @selection-change="handleUserSelectionChange"
          max-height="300"
        >
          <el-table-column type="selection" width="55" />
          <el-table-column prop="username" label="用户名" />
          <el-table-column prop="realName" label="真实姓名" />
          <el-table-column prop="phone" label="手机号" />
          <el-table-column prop="email" label="邮箱" />
        </el-table>
      </div>

      <!-- 员工信息设置 -->
      <div class="employee-info">
        <h4>员工信息</h4>
        <el-form :model="employeeForm" label-width="100px" :rules="rules" ref="formRef">
          <el-form-item label="职位" prop="position">
            <el-input v-model="employeeForm.position" placeholder="请输入职位" />
          </el-form-item>
          <el-form-item label="部门" prop="department">
            <el-input v-model="employeeForm.department" placeholder="请输入部门" />
          </el-form-item>
          <el-form-item label="员工编号" prop="employeeNo">
            <el-input v-model="employeeForm.employeeNo" placeholder="请输入员工编号" />
          </el-form-item>
          <el-form-item label="入职日期" prop="joinDate">
            <el-date-picker
              v-model="employeeForm.joinDate"
              type="date"
              placeholder="选择入职日期"
              style="width: 100%"
            />
          </el-form-item>
          <el-form-item label="备注">
            <el-input
              v-model="employeeForm.remark"
              type="textarea"
              placeholder="请输入备注信息"
              :rows="3"
            />
          </el-form-item>
        </el-form>
      </div>
    </div>

    <template #footer>
      <el-button @click="handleClose">取消</el-button>
      <el-button type="primary" @click="handleConfirmAdd" :loading="submitting">
        确认添加
      </el-button>
    </template>
  </el-dialog>
</template>

<script setup lang="ts">
import { ref, watch, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { propertyEmployeeApi } from '@/api/property/employee'
import type { UserVO } from '@/api/property/employee/types'
import { showSuccess, showError, showWarning } from '@/utils/message'

// Props
interface Props {
  visible: boolean
  propertyCompanyId: number
}

const props = defineProps<Props>()

// Emits
const emit = defineEmits<{
  'update:visible': [value: boolean]
  'success': []
}>()

// 响应式数据
const dialogVisible = ref(false)
const userLoading = ref(false)
const submitting = ref(false)
const userList = ref<UserVO[]>([])
const selectedUsers = ref<UserVO[]>([])

const searchForm = ref({
  keyword: ''
})

const employeeForm = ref({
  userId: 0,
  position: '',
  department: '',
  employeeNo: '',
  joinDate: null as Date | null,
  remark: ''
})

const formRef = ref<FormInstance>()

// 表单验证规则
const rules: FormRules = {
  position: [
    { required: true, message: '请输入职位', trigger: 'blur' }
  ],
  department: [
    { required: true, message: '请输入部门', trigger: 'blur' }
  ],
  employeeNo: [
    { required: true, message: '请输入员工编号', trigger: 'blur' }
  ],
  joinDate: [
    { required: true, message: '请选择入职日期', trigger: 'change' }
  ]
}

// 监听visible变化
watch(() => props.visible, (newVal) => {
  dialogVisible.value = newVal
  if (newVal) {
    resetForm()
  }
})

watch(dialogVisible, (newVal) => {
  emit('update:visible', newVal)
})

// 方法
const resetForm = () => {
  searchForm.value.keyword = ''
  employeeForm.value = {
    userId: 0,
    position: '',
    department: '',
    employeeNo: '',
    joinDate: null,
    remark: ''
  }
  userList.value = []
  selectedUsers.value = []
  formRef.value?.clearValidate()
}

const handleClose = () => {
  dialogVisible.value = false
}

const handleSearchUser = async () => {
  if (!searchForm.value.keyword.trim()) {
    showWarning('请输入搜索关键词')
    return
  }

  try {
    userLoading.value = true
    const { data } = await propertyEmployeeApi.searchAvailableUsers(
      searchForm.value.keyword,
      props.propertyCompanyId
    )
    userList.value = data
  } catch (error) {
    showError('搜索用户失败')
  } finally {
    userLoading.value = false
  }
}

const handleUserSelectionChange = (selection: UserVO[]) => {
  selectedUsers.value = selection
  if (selection.length === 1) {
    employeeForm.value.userId = selection[0].id
  } else {
    employeeForm.value.userId = 0
  }
}

const handleConfirmAdd = async () => {
  if (selectedUsers.value.length === 0) {
    showWarning('请选择要添加的用户')
    return
  }

  if (selectedUsers.value.length > 1) {
    showWarning('一次只能添加一个用户')
    return
  }

  try {
    await formRef.value?.validate()
  } catch (error) {
    return
  }

  try {
    submitting.value = true
    
    const addEmployeeDTO = {
      userId: employeeForm.value.userId,
      position: employeeForm.value.position,
      department: employeeForm.value.department,
      employeeNo: employeeForm.value.employeeNo,
      joinDate: employeeForm.value.joinDate?.toISOString().split('T')[0] || '',
      remark: employeeForm.value.remark
    }

    await propertyEmployeeApi.addEmployeeToPropertyCompany(
      props.propertyCompanyId,
      addEmployeeDTO
    )

    showSuccess('添加员工成功')
    emit('success')
  } catch (error) {
    showError('添加员工失败')
  } finally {
    submitting.value = false
  }
}
</script>

<style scoped>
.add-employee-container {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.user-selection,
.employee-info {
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  padding: 20px;
}

.user-selection h4,
.employee-info h4 {
  margin: 0 0 15px 0;
  color: #303133;
  font-size: 16px;
  font-weight: 500;
}

.user-selection {
  background-color: #fafafa;
}

.employee-info {
  background-color: #fff;
}
</style> 